﻿using System;
using System.Configuration;
using System.Web;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using mojoPortal.Web.RS.SBM.AppCode.Lib;

namespace mojoPortal.Web.RS.SBM.Controls
{
    public partial class ModalAddEstimateControl : RSBaseUserControl
    {

        protected void Page_Load(object sender, EventArgs e)
        {
        }

        public void ShowModal(int companyid, int locationid, int Estimateid)
        {
            hfRedirectURL.Value = "";
            lblMessage.Text = "Estimate";
            if (LoadEstimateDataByID(companyid, locationid))
            {
                btnSaveEstimate.Visible = true;
                SetControlEnabledState(true);
            }
            else
            {
                SetControlEnabledState(false);
            }
            mpeModalManageEstimate.Show();
        }

        public void SetControlEnabledState(bool bstate = false)
        {
            RSSBMCommonFunctions.SetControlsEnabledState(UpdatePanelManageEstimate.ContentTemplateContainer, bstate);
        }

        protected void btnReturn_Click(Object sender, EventArgs e)
        {
            if (hfRedirectURL.Value.Length > 0)
            {
                var nameValues = HttpUtility.ParseQueryString(Request.QueryString.ToString());
                nameValues.Set("tabindex", "3");
                string url = Request.Url.AbsolutePath;
                string updatedQueryString = "?" + nameValues.ToString();
                Response.Redirect(url + updatedQueryString);
            }
            else
            {
                mpeModalManageEstimate.Hide();
            }
        }
        protected void btnSaveEstimate_Click(Object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (userIdentity.RSCanWrite)
            {
                int CompanyId = userIdentity.RSCompanyId;

                int LocationId = hfLocationId.Value == "" ? 0 : Convert.ToInt32(hfLocationId.Value);
                int EstimateId = txtEstimateId.Text == "" ? 0 : Convert.ToInt32(txtEstimateId.Text);
                int ProjectId = hfProjectId.Value == "" ? 0 : Convert.ToInt32(hfProjectId.Value);

                int BillingContactId = ddlBillingContactId.SelectedValue == "" ? 0 : Convert.ToInt32(ddlBillingContactId.SelectedValue);
                string Term = txtTerm.Text.Trim();
                string PONumber = txtPONumber.Text.Trim();
                string AdditionalInstruction = txtAdditionalInstruction.Text.Trim();

                string WorkOrderName = txtWorkOrderName.Text.Trim();
                string StartDT = txtStartDate.Text + " " + txtStartTime.Text.Trim();
                string EndDT = txtEndDate.Text + " " + txtEndTime.Text.Trim();
                string Description = txtDescription.Text.Trim();
                string Response = txtResponse.Text.Trim();

                float LaborCost = txtLaborCost.Text == "" ? 0 : Convert.ToSingle(txtLaborCost.Text);
                int DiscountPercent = txtDiscountPercent.Text == "" ? 0 : Convert.ToInt32(txtDiscountPercent.Text);
                float DiscountAmount = txtDiscountAmount.Text == "" ? 0 : Convert.ToSingle(txtDiscountAmount.Text);

                int WorkOrderTypeID = Convert.ToInt32(ddlWorkOrderType.SelectedValue);
                int ScheduleTypeID = Convert.ToInt32(ddlScheduleType.SelectedValue);
                int StatusID = Convert.ToInt32(ddlEstimateStatus.SelectedValue);

                SqlCommand sqlCmd = new SqlCommand();

                SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@WorkOrderName", SqlDbType.NVarChar, 150, ParameterDirection.Input, WorkOrderName);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@Description", SqlDbType.NVarChar, -1, ParameterDirection.Input, Description);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@Response", SqlDbType.NVarChar, -1, ParameterDirection.Input, Response);

                if (StartDT.Trim().Length > 0)
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@StartDT", SqlDbType.DateTime, 0, ParameterDirection.Input, Convert.ToDateTime(StartDT));
                if (EndDT.Trim().Length > 0)
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@EndDT", SqlDbType.DateTime, 0, ParameterDirection.Input, Convert.ToDateTime(EndDT));

                SQLHelper.AddParamToSQLCmd(sqlCmd, "@LaborCost", SqlDbType.Money, 0, ParameterDirection.Input, LaborCost);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@DiscountPercent", SqlDbType.SmallInt, 0, ParameterDirection.Input, DiscountPercent);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@DiscountAmount", SqlDbType.Money, 0, ParameterDirection.Input, DiscountAmount);

                SQLHelper.AddParamToSQLCmd(sqlCmd, "@AdditionalInstructions", SqlDbType.NVarChar, 250, ParameterDirection.Input, AdditionalInstruction);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@Terms", SqlDbType.NVarChar, 250, ParameterDirection.Input, Term);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@PONumber", SqlDbType.NVarChar, 50, ParameterDirection.Input, PONumber);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@BillingContactId", SqlDbType.Int, 0, ParameterDirection.Input, BillingContactId);

                SQLHelper.AddParamToSQLCmd(sqlCmd, "@WorkOrderTypeID", SqlDbType.Int, 0, ParameterDirection.Input, WorkOrderTypeID);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@AppointmentTypeID", SqlDbType.Int, 0, ParameterDirection.Input, ScheduleTypeID);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@EstimateStatusId", SqlDbType.Int, 0, ParameterDirection.Input, StatusID);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@ProjectId", SqlDbType.Int, 0, ParameterDirection.Input, ProjectId);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@EstimateId", SqlDbType.Int, 0, ParameterDirection.Input, EstimateId);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@LocationId", SqlDbType.Int, 0, ParameterDirection.Input, LocationId);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@CompanyId", SqlDbType.Int, 0, ParameterDirection.Input, CompanyId);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@CurrentUser", SqlDbType.NVarChar, 25, ParameterDirection.Input, userIdentity.RSCurrentUser);
                if (ddlEstimateStatus.SelectedItem.Text.ToLower() == "accepted" || ddlEstimateStatus.SelectedItem.Text.ToLower() == "approved")
                {
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@EstimateAcceptedDT", SqlDbType.DateTime, 0, ParameterDirection.Input, DateTime.Today);
                }

                SQLHelper.SetCommandType(sqlCmd, CommandType.StoredProcedure, "rs_uspSaveEstimate");
                SQLHelper.ExecuteScalarCmd(sqlCmd);

                int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
                lblMessage.Text = "Estimate Successfully Saved!";
                lblMessage.ForeColor = System.Drawing.Color.DarkBlue;
                hfRedirectURL.Value = Request.RawUrl;
            }
            else
            {
                lblMessage.Text = "You Do Not Have Permission To Perform This Action!";
                lblMessage.ForeColor = System.Drawing.Color.DarkRed;
            }
            btnSaveEstimate.Visible = false;
            SetControlEnabledState(false);
        }

        public bool LoadEstimateDataByID(int companyid, int locationid)
        {
            bool ret = false;
            if (companyid > 0 && locationid > 0)
            {
                //ucLocationHeaderControl.LoadLocationHeader(companyid, locationid, false, false);

                RSSBMDataLookupLoader.LoadTypeDDL(companyid, "WORKORDER_CAT", ddlWorkOrderType);
                RSSBMDataLookupLoader.LoadTypeDDL(companyid, "SCHEDULE_CAT", ddlScheduleType);
                RSSBMDataLookupLoader.LoadStatusDDL(companyid, "ESTIMATE_CAT", ddlEstimateStatus);

                hfLocationId.Value = locationid.ToString();
                LoadBillingContactByLocationID(companyid, locationid);
                btnSaveEstimate.Visible = true;
                SetControlEnabledState(true);
                ret = true;
            }
            return ret;
        }

        private void LoadBillingContactByLocationID(int companyid, int locationid)
        {
            SqlCommand myCommand;
            SqlDataReader myDataReader;
            String sqlSELECT = "select c.ContactId, cast(c.ContactId as varchar(5)) + ' - ' + c.FirstName + ' ' + c.lastname as ContactName, c.BillingLocationId from rs_tblContact c inner join rs_tblContactLocation cl on c.contactid=cl.contactid where cl.LocationId=@locationid and cl.CompanyId=@companyid";
            SqlParameter param;
            SqlConnection myConnection;

            myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
            myCommand = new SqlCommand(sqlSELECT, myConnection);
            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@companyid";
            param.Value = companyid;
            myCommand.Parameters.Add(param);

            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@locationid";
            param.Value = locationid;
            myCommand.Parameters.Add(param);

            myConnection.Open();
            myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
            ddlBillingContactId.Items.Clear();
            ddlBillingContactId.DataSource = myDataReader;
            ddlBillingContactId.DataTextField = "contactname";
            ddlBillingContactId.DataValueField = "contactid";
            ddlBillingContactId.DataBind();
            ddlBillingContactId.Items.Insert(0, new ListItem("< Please select >", "0"));
            myConnection.Close();
        }
    }
}